const express = require('express')
const router = express.Router()
const { className } = require('../../models/className')

// 学生select列表班级
router.get('/list', (req, res) => {
    className.find().then(result => {
        res.status(200).json({
            code: 200,
            data: result.map(item => {
                return {
                    id: item._id,
                    value: item.grade + item.name,
                    label: item.grade + item.name
                }
            })
        })
    })
})

// 获取所有班级
router.get('/', (req, res) => {
    className.find().then(result => {
        console.log(result);
        res.status(200).json({
            code: 200,
            data: result.map(item => {
                return {
                    id: item._id,
                    name: item.name,
                    grade: item.grade,
                    createDate: item.createDate
                }
            })
        })
    })
})

// 新增班级
router.post('/', (req, res) => {
    const { name, grade } = req.body
    className.findOne({ name }).then(result => {
        if (result) return res.status(400).json({
            code: 200,
            msg: '班级已存在'
        })

        new className({
            name,
            grade
        }).save(() => {
            res.status(200).json({
                code: 200,
                msg: '添加成功'
            })
        })
    })
})

// 修改班级
router.put('/', (req, res) => {
    const { id, name, grade } = req.body
    const _id = id,
        $set = {
            name: name ? name : '',
            grade: grade ? grade : ''
        }
    className.findOneAndUpdate({ _id }, { $set }, { new: true }).then(() => {
        res.status(200).json({
            code: 200,
            msg: '修改成功'
        })
    }).catch(error => {
        res.status(500).json({
            code: 500,
            msg: '修改失败'
        })
    })
})

// 删除班级
router.delete('/', (req, res) => {
    className.findOneAndRemove({ _id: req.body.id }).then(() => {
        res.status(200).json({
            code: 200,
            msg: '删除成功'
        })
    })
})

module.exports = router